package com.ocom.webapi.controller;


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.ocom.common.constant.WebApiServiceUrl;
import com.ocom.common.entity.human.EntityPersonnelInfo;
import com.ocom.common.entity.master.EntityFileDownloadInfo;
import com.ocom.common.entity.payconfig.CouponsItem;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.payconfig.CouponsDataExportRequest;
import com.ocom.common.request.payconfig.SubsidyDataRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.human.GetPersonAndAccountVo;
import com.ocom.common.vo.human.UserListRVo;
import com.ocom.common.vo.human.UserListVo;
import com.ocom.common.vo.payconfig.*;
import com.ocom.security.authentication.YoCiUser;
import com.ocom.security.utils.SecurityUtils;
import com.ocom.webapi.feign.AccessClientService;
import com.ocom.webapi.feign.HumanClientService;
import com.ocom.webapi.feign.MqSubsidyClientService;
import com.ocom.webapi.feign.PayConfigClientService;
import com.ocom.webapi.service.CouponsVoucherService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@PreAuthorize("@pms.hasRole('ROLE_WEB')" )
@RestController
@AllArgsConstructor
public class CouponsVoucherController {

    @Resource
    private PayConfigClientService payConfigClientService;
    @Resource
    private CouponsVoucherService couponsVoucherService;
    @Autowired
    private HumanClientService humanClientService;
    @Autowired
    private AccessClientService accessClientService;
    @Autowired
    private MqSubsidyClientService maPayClientService;


    /**
     * 7.4.1赠券批次列表
     * @param params
     * @return
     */
    @PostMapping(WebApiServiceUrl.Url_CouponsVoucherOnShow)
    public Result couponsItem(@RequestBody CouponsItemVo params){
        Result result = payConfigClientService.couponsItem(params);
        JSONObject retJsonObject = JSON.parseObject(JSON.toJSONString(result.getData()));
        List<CouponsItemRVo> lists = JSON.parseArray(JSON.toJSONString(retJsonObject.get("list")),CouponsItemRVo.class);
        long lTotal = retJsonObject.getLong("total");
//        List<CouponsItemRVo> lists =  JSON.parseArray(sLists,CouponsItemRVo.class);
//        System.out.println("lists====" + lists.size() +lists);
        String orderNo = "";
        Map<String,Object> map = new HashMap<>();
        ArrayList<CouponsItemRVo> arrayList = new ArrayList<>();
        for(CouponsItemRVo list: lists){
            if(list.getMode()==0){
                orderNo = "M"+list.getCouponsItemId();
            }else if(list.getMode() > 0){
                orderNo = "A"+list.getCouponsItemId();
            }
            CouponsNumberRVo numberRVo = payConfigClientService.couponsNumber(params.getComId(),orderNo);
            list.setOrderNo(orderNo);
            if(numberRVo != null){
                list.setPersonNumber(numberRVo.getPersonNumber());
                list.setVoucherNumber(numberRVo.getVoucherNumber());
                list.setUsedNumber(numberRVo.getUsedNumber());
            }
            arrayList.add(list);
        }
        map.put("itemList", arrayList);
        map.put("total",lTotal);
        return ResultUtil.success(map);
    }

    /**
     * 添加赠券数据
     * @param addCoupons
     * @return
     */
    @PostMapping(WebApiServiceUrl.Url_CouponsVoucherAddPerson)
    public Result addCouponsData(@RequestBody @Valid AddCouponsDataVo addCoupons) {

        List<Long> pIds = null;
        List<String> deptIdList = new ArrayList<>();
        if (null != addCoupons.getDeptId() && 0 < addCoupons.getDeptId()) {
            deptIdList.add(addCoupons.getDeptId().toString());
        }

        List<String> pTags = new ArrayList<>();
        if(ObjectUtil.isNotEmpty(addCoupons.getTag())){
            pTags.add(addCoupons.getTag());
        }


        if (ObjectUtil.isNotEmpty(addCoupons.getAccType())) {
            List<Integer> accTypes = Arrays.stream(addCoupons.getAccType().split(",")).map(Integer::valueOf).collect(Collectors.toList());
            if(accTypes.size()<=0){
                return ResultUtil.error(ResultEnum.Err_4201);
            }
            GetPersonAndAccountVo getPersonAndAccountVo = new GetPersonAndAccountVo();
            getPersonAndAccountVo.setComId(addCoupons.getComId());
            getPersonAndAccountVo.setAccType(accTypes);
            getPersonAndAccountVo.setDeptIdList(deptIdList);
            getPersonAndAccountVo.setPTags(pTags);
            Result result = payConfigClientService.getPersonAndAccount(getPersonAndAccountVo);
            if (200 != result.getCode()) {
                return result;
            }
            List<EntityPersonnelInfo> entityPersonnelInfos = JSON.parseArray(JSON.toJSONString(result.getData()), EntityPersonnelInfo.class);
            pIds = entityPersonnelInfos.stream().map(EntityPersonnelInfo::getPId).collect(Collectors.toList());
        } else {
            UserListVo userListVo = new UserListVo();
            userListVo.setComId(addCoupons.getComId());
            userListVo.setStatus(0);
            userListVo.setDeptId(addCoupons.getDeptId());
            userListVo.setPCode(addCoupons.getPCode());
            userListVo.setPName(addCoupons.getPName());
            userListVo.setPage(1);
            userListVo.setSize(Integer.MAX_VALUE);//TODO
            Result result = humanClientService.GetPersonnelList(userListVo);
            if (200 != result.getCode()) {
                return result;
            }
            PageInfo pageInfo = JSON.parseObject(JSON.toJSONString(result.getData()), PageInfo.class);
            List<UserListRVo> userListRVos = JSON.parseArray(JSON.toJSONString(pageInfo.getList()), UserListRVo.class);
            pIds = userListRVos.stream().map(UserListRVo::getPId).collect(Collectors.toList());
        }

        if(pIds != null && pIds.size() > 0){
            addCoupons.setPIds(pIds);
           return payConfigClientService.addCouponsData(addCoupons);

        }else{
            return ResultUtil.error(ResultEnum.Err_4201);
        }
    }

    /**
     * 4.2赠券数据列表
     * @param couponsDataVo
     * @return
     */
    @PostMapping(WebApiServiceUrl.Url_CouponsVoucherVoucherList)
    public Result couponsDataList(@RequestBody @Valid CouponsDataListVo couponsDataVo){
        return payConfigClientService.couponsDataList(couponsDataVo);
    }

    /**
     * 7.4.4修改赠券数据
     * @param request
     * @return
     */
    @PostMapping(WebApiServiceUrl.Url_CouponsVoucherModifyNumber)
    public Result changeCouponsNumber(@RequestBody @Valid ChangeCouponsNumberVo request){
        return payConfigClientService.changeCouponsNumber(request);
    }

    /**
     * 中止赠券使用
     * @param request
     * @return
     */
    @PostMapping(WebApiServiceUrl.Url_CouponsVoucherBreak)
    public Result breakCoupons(@RequestBody @Valid BreakCouponsVo request){
        Result result = payConfigClientService.breakCoupons(request);
        if(result.getCode() != 200){
            return ResultUtil.error(3026);
        }
        String orderNo = request.getOrderNo();
        if(orderNo.startsWith("M") || orderNo.startsWith("A")){
            orderNo = orderNo.substring(1);
            Integer iorderNo = Integer.parseInt(orderNo);
            System.out.println("comId111==="+request.getComId());
            return payConfigClientService.updateCouponsItemById(request.getComId(),iorderNo,3,new Date());
        }
        return ResultUtil.info(4124,"无操作数据");
    }

    /**
     * 7.4.6发放赠券
     * @param request
     * @return
     */
/*    @PostMapping(WebApiServiceUrl.Url_CouponsVoucherGrant)
    public Result grantCoupons(@RequestBody @Valid GrantCouponsVo request){
        Result result = payConfigClientService.grantCoupons(request);
        if(result.getCode() != 200){
            return ResultUtil.error(3026);
        }
        String orderNo = request.getOrderNo();
        if(orderNo.startsWith("M") || orderNo.startsWith("A")){
            orderNo = orderNo.substring(1);
            Integer iorderNo = Integer.parseInt(orderNo);
            return payConfigClientService.updateCouponsItemById(request.getComId(),iorderNo,1,new Date());
        }
        return ResultUtil.info(4124,"无操作数据");
    }*/

    @PostMapping(WebApiServiceUrl.Url_CouponsVoucherGrant)
    public Result grantCoupons(@RequestBody @Valid GrantCouponsVo request) {
        log.info("发放赠券 开始有效日期: " + request.getStartDate());
        Result result = payConfigClientService.grantCoupons(request);
        return result;
    }


    /**
     *7.4.11增加赠券发放批次
     * @param couponsItem
     * @return
     */
    @PostMapping(WebApiServiceUrl.Url_CouponsVoucherAddItem)
    public Result newCouponsItem(@RequestBody CouponsItem couponsItem){
        return payConfigClientService.newCouponsItem(couponsItem);
    }



    /**
     * 7.4.12修改赠券发放批次
     * @param couponsItem
     * @return
     */
    @PostMapping(WebApiServiceUrl.Url_CouponsVoucherModifyItem)
    public Result updateCouponsItem(@RequestBody CouponsItem couponsItem){
        log.info("修改赠券发放批次...");
        return payConfigClientService.updateCouponsItem(couponsItem);
    }

    //7.4.10导入赠券数据
    @PostMapping(WebApiServiceUrl.Url_CouponsVoucherImport)
    public Result couponsVoucherImport(@RequestParam("comId") Long comId,@RequestParam("orderNo") String orderNo, @RequestPart("file") MultipartFile file){
        return couponsVoucherService.couponsVoucherImport(comId,orderNo,file);
    }

    @PostMapping(WebApiServiceUrl.Url_deleteVoucherDataByIds)
    public Result deleteVoucherDataByIds(@RequestBody IdsVo ids){
        return payConfigClientService.deleteVoucherDataByIds(ids);
    }

    //7.4.7导出消费券数据（CouponsVoucher/exportData）
    @PostMapping(WebApiServiceUrl.URL_CouponsVoucherExportData)
    public Result couponsVoucherExportData(@RequestBody CouponsDataExportRequest request){
        EntityFileDownloadInfo entityFileDownloadInfo=new EntityFileDownloadInfo();
        YoCiUser yoCiUser= SecurityUtils.getYoCiUser();
        entityFileDownloadInfo.setPId(yoCiUser.getId());
        entityFileDownloadInfo.setName("导出消费券数据");
        entityFileDownloadInfo.setStatus(0l);
        Result result=accessClientService.SendExcelApply(entityFileDownloadInfo);
        if(result.getCode()!=200){
            return ResultUtil.error(ResultEnum.Err_4013);
        }
        request.setId((Integer)result.getData());
        return maPayClientService.couponsDataExport(request);
    }

}
